package org.bluedream.core.module.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bluedream.comm.base.BaseController;
import org.bluedream.core.module.sys.entity.Menu;
import org.bluedream.core.module.sys.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("${adminPath}/menu")
public class MenuController extends BaseController {
    @Resource
    private MenuService menuService;

    @ModelAttribute
    public Menu get(String id){
        return menuService.getById(id);
    }

    @RequiresPermissions("menu:view")
    @RequestMapping(value = {"/list" , ""})
    public String list(Menu menu, Model model){
        model.addAttribute("menu" , menu);
        return "sys/menu/menuList";
    }

    @RequiresPermissions("menu:view")
    @RequestMapping("/form")
    public String form(Menu menu, Model model){
        menu = menuService.createNextNode(menu);
        model.addAttribute("menu" , menu);
        return "sys/menu/menuForm";
    }

    @RequiresPermissions("menu:view")
    @RequestMapping("/findPage")
    @ResponseBody
    public IPage<Menu> findPage(Menu menu){
        return menuService.findPage(menu);
    }


    @RequiresPermissions("menu:view")
    @RequestMapping("/treeData")
    @ResponseBody
    public List<Map<String , Object>> treeData(@RequestParam(defaultValue="1")String isShowCode , @RequestParam(defaultValue="undefined")String excludeCode){
        return menuService.treeData(excludeCode , isShowCode);
    }

    @RequiresPermissions("menu:edit")
    @RequestMapping("/save")
    @ResponseBody
    public String save(Menu menu){
        boolean flag = menuService.save(menu);
        if (flag){
            return "菜单信息保存成功";
        }
        return "菜单信息保存失败";
    }

    /**
     * 创建下一节点
     * @param menu
     * @return
     */
    @RequiresPermissions("menu:edit")
    @RequestMapping(value = "/createNextNode" , method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Menu createNextNode(@RequestBody Menu menu){
        return menuService.createNextNode(menu);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Menu menu){
        try {
            boolean flag = menuService.delete(menu);
            if (flag){
                return "菜单信息删除成功";
            }
            return "菜单信息删除失败";
        }catch (Exception e1){
            return e1.getMessage();
        }
    }
}
